package com.ren.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ren.feign.entity.ReclUserVo;
import com.ren.user.entity.ReclUser;
import com.ren.user.mapper.ReclUserMapper;
import com.ren.user.service.ReclUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ren.utils.encrypt.MD5;
import com.ren.utils.exception.ReclException;
import com.ren.utils.jwt.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author RZY
 * @since 2022-07-13
 */
@Service
public class ReclUserServiceImpl extends ServiceImpl<ReclUserMapper, ReclUser> implements ReclUserService {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public List<ReclUserVo> getRemoteFmUsersInfo(List<Long> userIds) {
        return this.baseMapper.getRemoteFmUsersInfo(userIds);
    }

    @Override
    public ReclUserVo getRemoteFmUserInfoById(Long userId) {
        return this.baseMapper.getRemoteFmUserInfoById(userId);
    }

    @Override
    public List<ReclUserVo> getRemoteArticleUsersInfo(List<Long> userIds) {
        return this.baseMapper.getRemoteArticleUsersInfo(userIds);
    }

    @Override
    public ReclUserVo getRemoteArticleUserInfoById(Long userId) {
        return this.baseMapper.getRemoteArticleUserInfoById(userId);
    }

    /**
     *
     * @param reclUser 用户登录信息（包含账号、密码）
     * @return 返回登录成功生成的token令牌
     */
    @Override
    public String doLogin(ReclUser reclUser) {
        //获取用户登录账号以及密码
        String account = reclUser.getAccount();
        String password = reclUser.getPassword();
        //账号密码非空验证
        if (account == null || password == null) throw new ReclException(20001, "请输入账号和密码！");
        //验证账号存在并获取DB中账户密码
        ReclUser dbUser = this.getOne(new LambdaQueryWrapper<ReclUser>()
                .eq(ReclUser::getAccount, account)
                .select(ReclUser::getPassword,
                        ReclUser::getIsDisabled,
                        ReclUser::getId,
                        ReclUser::getNickName));
        //获取数据库密码
        String actualPassword = dbUser.getPassword();
        //验证账号不存在返回错误信息
        if(!StringUtils.isEmpty(actualPassword)) throw new ReclException(20001, "账号不存在，请输入正确账号！");
        //MD5对password加密并比对DB正确密码，验证失败直接返回错误信息
        if(!MD5.encrypt(password).equals(actualPassword)) throw new ReclException(20001, "密码错误，请重新输入！");
        //密码验证成功，判断用户是否被禁用
        Boolean isDisabled = dbUser.getIsDisabled();
        if(isDisabled) throw new ReclException(20001, "账户已被禁用，登录失败！");
        //验证成功，返回token
        return JwtUtils.getJwtToken(String.valueOf(dbUser.getId()), dbUser.getNickName());
    }

    /**
     *
     * @param reclUser 用户注册信息
     * @return 返回注册结果
     */
    @Override
    public boolean doRegister(ReclUser reclUser) {
        //判断用户注册信息是否完善
        String account = reclUser.getAccount();
        String password = reclUser.getPassword();
        String nickName = reclUser.getNickName();
        String code = reclUser.getCode();
        if(!StringUtils.isEmpty(account)) throw new ReclException(20001, "请输入账号!");
        if(!StringUtils.isEmpty(password)) throw new ReclException(20001, "请输入密码!");
        if(!StringUtils.isEmpty(nickName)) throw new ReclException(20001, "请输入用户昵称!");
        if(!StringUtils.isEmpty(code)) throw new ReclException(20001, "请输入有效验证码");
        //从Redis中获取验证码进行比对
        String redisCode = redisTemplate.opsForValue().get(account);
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) throw new ReclException(20001, "验证码错误，请输入正确验证码");
        //判断账户是否已存在
        int count = this.count(new LambdaQueryWrapper<ReclUser>().eq(ReclUser::getAccount, account));
        if(count > 0) throw new ReclException(20001, "账号已被注册!");
        //成功注册，保存注册信息
        reclUser.setPassword(MD5.encrypt(password)); //MD5对密码加密
        return this.save(reclUser);
    }

    @Override
    public ReclUser getReclUserByJWT(HttpServletRequest request) {
        //获取请求头中的token令牌
        String token = request.getHeader("token");
        //获取token中的用户id
        String id = JwtUtils.getMemberIdByJwtToken(request);
        //查询用户信息
        return this.getById(id);
    }
}
